package qf.sail.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import qf.sail.dao.OrderItemDao;
import qf.sail.entity.OrderItem;
import qf.sail.util.DBUtil;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.List;

public class OrderItemDaoImpl implements OrderItemDao {

    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    /**
     * 插入订单子项，返回id
     * @param orderItem
     * @return
     */
    @Override
    public Long addOrderItem(OrderItem orderItem) {
        String sql = "INSERT INTO order_item (size,color,count,good_id,order_id) VALUES (?,?,?,?,?)";
        Object[] params = {orderItem.getSize(),orderItem.getColor(),orderItem.getCount(),orderItem.getGoodId(),orderItem.getOrderId()};
        try {
            BigInteger id = queryRunner.insert(sql, new ScalarHandler<BigInteger>(), params);
            return id.longValue();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 0L;
        }
    }

    /**
     * 根据订单id，查询订单子项
     * @param orderId
     * @return
     */
    @Override
    public List<OrderItem> getItemsByOrderId(long orderId) {
        String sql = "select * from `order_item` where order_id = ?";
        Object[] params = {orderId};
        List<OrderItem> items = null;
        try {
            items = queryRunner.query(sql, DBUtil.getBeanListHandler(OrderItem.class),params);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return items;
    }

    /**
     * 插入购物车子项，返回id
     * @param orderItem
     * @return
     */
    @Override
    public Long addItemToShopCar(OrderItem orderItem) {
        String sql = "INSERT INTO order_item (size,color,count,good_id,shop_car_id) VALUES (?,?,?,?,?)";
        Object[] params = {orderItem.getSize(),orderItem.getColor(),orderItem.getCount(),orderItem.getGoodId(),orderItem.getShopCarId()};
        try {
            BigInteger id = queryRunner.insert(sql, new ScalarHandler<BigInteger>(), params);
            return id.longValue();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 0L;
        }
    }

    @Override
    public List<OrderItem> getItemsByShopCarId(long shopCarId) {
        String sql = "select * from `order_item` where shop_car_id = ?";
        Object[] params = {shopCarId};
        List<OrderItem> items = null;
        try {
            items = queryRunner.query(sql, DBUtil.getBeanListHandler(OrderItem.class),params);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return items;
    }
}
